package image

import (
	"encoding/json"
	"github.com/pkg/errors"
	"io/ioutil"
	"log"
)

//ParseLayersFromManifest 从manifest文件解析出layer层信息
func ParseLayersFromManifest(manifestSrcPath string) ([]string, error) {
	var (
		err     error
		mf      []ManiFest
		content []byte
	)

	content, err = ioutil.ReadFile(manifestSrcPath)
	if err != nil || len(content) == 0 {
		log.Println("ioutil.ReadFile error or file content is empty!")
		return nil, err
	}

	//2.解析 manifest.json 内容的各个字段
	err = json.Unmarshal(content, &mf)
	if err != nil {
		return nil, err
	}

	//3.解析内容为空
	if len(mf) == 0 || len(mf[0].Layers) == 0 {
		return nil, errors.New("can't handle empty manifest!")
	}

	//4.大于一个的manifest
	if len(mf) > 1 {
		return nil, errors.New("can't handle multiple manifest object!")
	}

	return mf[0].Layers, nil
}
